using System;
using System.Web;

namespace Website
{
    public static class HttpRequestBaseExtensionMethods
    {
        public static bool Accepts(this HttpRequestBase arg, string type, string subtype)
        {
            return Accepts(arg, type, subtype, true);
        }

        public static bool Accepts(this HttpRequestBase arg, string type, string subtype, bool any)
        {
            if (null == arg)
            {
                throw new ArgumentNullException("arg");
            }

            if (null == type)
            {
                throw new ArgumentNullException("type");
            }

            if (0 == type.Length)
            {
                throw new ArgumentOutOfRangeException("type");
            }

            if (null == subtype)
            {
                throw new ArgumentNullException("subtype");
            }

            if (0 == subtype.Length)
            {
                throw new ArgumentOutOfRangeException("subtype");
            }

            bool accepts = !arg.Headers["Accept"].IsNullOrEmpty();

            if (accepts)
            {
                accepts = false;
                foreach (string item in arg.AcceptTypes)
                {
                    if (any && item.Contains("*/*"))
                    {
                        accepts = true;
                        break;
                    }
                    else if (any && item.Contains(type + "/*"))
                    {
                        accepts = true;
                        break;
                    }
                    else if (item.Contains(String.Concat(type, "/", subtype)))
                    {
                        accepts = true;
                        break;
                    }
                }
            }

            return accepts;
        }
    }
}